import AMapLoader from "@amap/amap-jsapi-loader";
import { AMAP_MAP_KEY, AMAP_SECRET_KEY } from "../config";

const MAX_RETRY_COUNT = 3; // 最大重试次数
let retryCount = 0; // 当前重试次数
let mapPromise: Promise<any> | null = null;

/**
 * 加载高德地图API
 * @param {Object} options - 配置选项
 * @param {Array} [options.plugins=[]] - 需要加载的插件列表
 * @param {string} [options.version='2.0'] - API版本
 * @returns {Promise} 返回地图加载Promise
 */
interface ExtendsWindow extends Window {
  _AMapSecurityConfig?: {
    securityJsCode: string;
  };
}

let _window: ExtendsWindow = window;

interface AMapOptions {
  plugins?: any[];
  version?: string;
}

/**
 * 加载高德地图API
 * @param {AMapOptions} options - 配置选项
 * @param {Array} [options.plugins=[]] - 需要加载的插件列表
 * @param {string} [options.version='2.0'] - API版本
 * @returns {Promise} 返回地图加载Promise
 */
export const loadAMap = (options: AMapOptions = {}): Promise<any> => {
  if (mapPromise) {
    // eslint-disable-next-line
    // @ts-ignore
    // AMapLoader.reset(); //重置地图
    return mapPromise;
  }
  const { plugins = [], version = "2.0" } = options;

  _window._AMapSecurityConfig = {
    securityJsCode: AMAP_SECRET_KEY
  };

  mapPromise = new Promise((resolve, reject) => {
    const load = () => {
      AMapLoader.load({
        key: AMAP_MAP_KEY,
        version,
        plugins
      })
        .then(resolve)
        .catch(error => {
          if (retryCount < MAX_RETRY_COUNT) {
            retryCount++;
            console.warn(`地图加载失败，第${retryCount}次重试...`);
            setTimeout(load, 1000 * retryCount);
          } else {
            console.error("地图加载最终失败:", error);
            mapPromise = null;
            retryCount = 0;
            reject(error);
          }
        });
    };

    load();
  });

  return mapPromise;
};

/**
 * 清除地图加载缓存
 */
export const clearAMapCache = () => {
  mapPromise = null;
  retryCount = 0;
};
